﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Microsoft.Office.Interop.Excel;

namespace RESP_IIWaterAssessment
{
    public partial class FarmIndicatorsRepForm : Form
    {
        public FarmIndicatorsRepForm()
        {
            InitializeComponent();
        }

        int regID, avpID, fhID = -1, cultID, year = DateTime.Now.Year;

        private void FarmIndicatorsRepForm_Load(object sender, EventArgs e)
        {
            cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;
            cbRegion.DataSource = UtilClass.FillCBRegions();
            cbRegion.DisplayMember = "Name";
            cbRegion.ValueMember = "ID";

            if (InformationClass.isAdmin)
            {
                cbRegion.SelectedIndex = -1;
                cbRegion.Text = string.Empty;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
            }
            else
            {
                cbRegion.Enabled = false;
                regID = InformationClass.regionID;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
                cbRegion.SelectedValue = regID;
                cbRegion_SelectedIndexChanged(cbRegion, null);
                cbAVP.Enabled = true;
                cbAVP.Text = string.Empty;
                //toolStrip1.Visible = false;
            }

            for (int i = 1991; i < 2100; i++)
            {
                cbYear.Items.Add(i);
            }
            cbYear.SelectedIndex = cbYear.FindStringExact(DateTime.Now.Year.ToString());

            cbCulture.SelectedIndexChanged -= cbCulture_SelectedIndexChanged;
            cbCulture.DataSource = UtilClass.GetCBCultureDataSourse();
            cbCulture.DisplayMember = "Name";
            cbCulture.ValueMember = "ID";
            cbCulture.SelectedIndex = -1;
            cbCulture.SelectedIndexChanged += new EventHandler(cbCulture_SelectedIndexChanged);
        }

        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbRegion.SelectedIndex >= 0)
            {
                cbAVP.Enabled = true;
                regID = Convert.ToInt32(cbRegion.SelectedValue);
                cbAVP.SelectedIndexChanged -= cbAVP_SelectedIndexChanged;
                cbAVP.DataSource = UtilClass.FillAVP(regID);
                cbAVP.ValueMember = "ID";
                cbAVP.DisplayMember = "Name";
                cbAVP.SelectedIndex = -1;
                cbAVP.Text = string.Empty;
                cbFH.DataSource = null;
                cbAVP.SelectedIndexChanged += new EventHandler(cbAVP_SelectedIndexChanged);

            }
        }

        private void cbAVP_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbAVP.SelectedIndex >= 0)
            {
                avpID = Convert.ToInt32(cbAVP.SelectedValue);
                cbFH.SelectedIndexChanged -= cbFH_SelectedIndexChanged;
                cbFH.Enabled = true;
                cbFH.DataSource = DBClass.Farms
                    .Where(wh => wh.AVPID == avpID)
                    .Select(se => new { ID = se.ID, Name = se.Name })
                    .OrderBy(o => o.Name)
                    .ToArray();
                cbFH.DisplayMember = "Name";
                cbFH.ValueMember = "ID";
                cbFH.SelectedIndex = -1;
                cbFH.Text = string.Empty;
                cbFH.SelectedIndexChanged += new EventHandler(cbFH_SelectedIndexChanged);
            }
        }

        private void cbFH_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbFH.SelectedIndex >= 0)
            {
                fhID = Convert.ToInt32(cbFH.SelectedValue);
            }
            else
                fhID = 0;
        }

        private void cbCulture_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbCulture.SelectedIndex >= 0)
            {
                cultID = Convert.ToInt32(cbCulture.SelectedValue);
            }
            else
                cultID = 0;
        }

        private void cbYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            Int32.TryParse(cbYear.Text, out year);
        }

        private void chbYear_CheckedChanged(object sender, EventArgs e)
        {
            cbYear.Enabled = chbYear.Checked;
        }

        private void chbCulture_CheckedChanged(object sender, EventArgs e)
        {
            cbCulture.Enabled = chbCulture.Checked;
        }

        private void buttonShow_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(DBClass.ConStr);
            SqlCommand com = new SqlCommand("FarmIndicatorReport", con);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.Add("@Lang", SqlDbType.Bit).Value = InformationClass.Lang;
            com.Parameters.Add("@FarmID", SqlDbType.Int).IsNullable = true;
            com.Parameters.Add("@CultureID", SqlDbType.Int).IsNullable = true;
            com.Parameters.Add("@Year", SqlDbType.Int).IsNullable = true;

            if (chbFH.Checked && fhID > 0)
                com.Parameters["@FarmID"].Value = fhID;
            else
                com.Parameters["@FarmID"].Value = DBNull.Value;

            if (chbCulture.Checked && cultID > 0)
                com.Parameters["@CultureID"].Value = cultID;
            else
                com.Parameters["@CultureID"].Value = DBNull.Value;

            if (chbYear.Checked && year >= 1991)
                com.Parameters["@Year"].Value = year;
            else
                com.Parameters["@Year"].Value = DBNull.Value;

            System.Data.DataTable tab = new System.Data.DataTable("Rep");
            SqlDataAdapter adapter = new SqlDataAdapter(com);
            try
            {
                adapter.Fill(tab);
                dgvReport.DataSource = tab;

                if (InformationClass.Lang)
                {
                    dgvReport.Columns["Date"].HeaderText = "Год";
                    dgvReport.Columns["Indicator"].HeaderText = "Индикатор";
                }
                else
                {
                    dgvReport.Columns["Date"].HeaderText = "Йил";
                    dgvReport.Columns["Indicator"].HeaderText = "Индикатор";
                }
                dgvReport.AutoResizeColumns();
            }
            catch (Exception ex)
            {
                MessageBox.Show(msgClass.msgNoData, msgClass.msgAchtung);
                dgvReport.DataSource = null;
            }
        }

        private void dgvReport_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex.Equals(dgvReport.Columns["Date"].Index) && e.Value != null)
            {
                e.Value = ((DateTime)e.Value).Year.ToString();
            }
            if (e.ColumnIndex.Equals(dgvReport.Columns["Indicator"].Index) && e.Value != null)
            {
                switch (e.Value.ToString())
                {
                    case "Area":
                        e.Value = InformationClass.Lang ? "Площадь" : "Майдон";
                        break;
                    case "WaterQuantity":
                        e.Value = InformationClass.Lang ? "Количество использованной воды" : "Фойдаланилган сув миқдори";
                        break;
                    case "HarvestQuantity":
                        e.Value = InformationClass.Lang ? "Количество собранного урожая" : "Йиғиб орлингна ҳосил миқдори";
                        break;
                    case "HarvestCost":
                        e.Value = InformationClass.Lang ? "Стоимость урожая" : "Ҳосил нарҳи";
                        break;
                    case "AgricultureLoss":
                        e.Value = InformationClass.Lang ? "Общие затраты на с/х производство" : "Қ/х ишлаб чиқариши учун умумий ҳаражатлар";
                        break;
                    case "Profit":
                        e.Value = InformationClass.Lang ? "Общая прибыль" : "Умумий даромад";
                        break;
                    case "Tax":
                        e.Value = InformationClass.Lang ? "Налоги и др. расходы" : "Солиқлар ва бошқа ҳаражатлар";
                        break;
                    case "NetProfit":
                        e.Value = InformationClass.Lang ? "Чистая прибыль" : "Соф фойда";
                        break;
                    case "Productivity":
                        e.Value = InformationClass.Lang ? "Продуктивность воды" : "Сув унумдорлиги";
                        break;
                    case "Profitability":
                        e.Value = InformationClass.Lang ? "Рентабельность производства" : "Ишлаб чиқариш рентабеллилиги";
                        break;
                    case "Investment":
                        e.Value = InformationClass.Lang ? "Отдача на инвестиции" : "Инвестициялардан олинган фойда";
                        break;
                    default:
                        break;
                }
            }
        }

        private void buttonExcel_Click(object sender, EventArgs e)
        {
            if (dgvReport.RowCount > 0)
            {
                MessageBox.Show(msgClass.msgWaiting);
                GetReport();
                excelapp.Visible = true;
            }
        }

        Sheets excelsheets;
        Worksheet excelworksheet;
        Microsoft.Office.Interop.Excel.Application excelapp;
        Workbook excelappworkbook;

        private void GetReport()
        {
            excelapp = new Microsoft.Office.Interop.Excel.Application();
            excelapp.SheetsInNewWorkbook = 1;

            if (InformationClass.Lang)
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i25r20.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            else
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i25r20uz.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            excelappworkbook = excelapp.Workbooks[1];
            excelsheets = excelappworkbook.Worksheets;// .Worksheets[0]; //Sheets 

            int numPage = 1, left = 5, top = 11;

            excelworksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelsheets.get_Item(numPage);

            excelworksheet.Cells.NumberFormat = "@";

            excelworksheet.Cells[4, 3] = cbRegion.Text;
            excelworksheet.Cells[5, 3] = cbAVP.Text;
            excelworksheet.Cells[6, 3] = cbFH.Text;

            if (chbYear.Checked)
                excelworksheet.Cells[7, 3] = cbYear.Text;

            for (int i = 2; i < dgvReport.ColumnCount; i++)
            {
                excelworksheet.Cells[10, i + 3] = dgvReport.Columns[i].HeaderText;
                addBorder(excelworksheet.Cells[10, i + 3]);

                for (int j = 0; j < dgvReport.RowCount; j++)
                {
                    if (dgvReport[1, j].Value.ToString().Equals("Area"))
                    {
                        excelworksheet.Cells[11, 3 + i] = dgvReport[i, j].Value;
                        addBorder(excelworksheet.Cells[11, 3 + i]);
                        continue;
                    }
                    if (dgvReport[1, j].Value.ToString().Equals("WaterQuantity"))
                    {
                        excelworksheet.Cells[12, 3 + i] = dgvReport[i, j].Value;
                        addBorder(excelworksheet.Cells[12, 3 + i]);
                        continue;
                    }
                    if (dgvReport[1, j].Value.ToString().Equals("HarvestQuantity"))
                    {
                        excelworksheet.Cells[13, 3 + i] = dgvReport[i, j].Value;
                        addBorder(excelworksheet.Cells[13, 3 + i]);
                        continue;
                    }
                    if (dgvReport[1, j].Value.ToString().Equals("HarvestCost"))
                    {
                        excelworksheet.Cells[14, 3 + i] = dgvReport[i, j].Value;
                        addBorder(excelworksheet.Cells[14, 3 + i]);
                        continue;
                    }
                    if (dgvReport[1, j].Value.ToString().Equals("AgricultureLoss"))
                    {
                        excelworksheet.Cells[15, 3 + i] = dgvReport[i, j].Value;
                        addBorder(excelworksheet.Cells[15, 3 + i]);
                        continue;
                    }
                    if (dgvReport[1, j].Value.ToString().Equals("Profit"))
                    {
                        excelworksheet.Cells[16, 3 + i] = dgvReport[i, j].Value;
                        addBorder(excelworksheet.Cells[16, 3 + i]);
                        continue;
                    }
                    if (dgvReport[1, j].Value.ToString().Equals("Tax"))
                    {
                        excelworksheet.Cells[17, 3 + i] = dgvReport[i, j].Value;
                        addBorder(excelworksheet.Cells[17, 3 + i]);
                        continue;
                    }
                    if (dgvReport[1, j].Value.ToString().Equals("NetProfit"))
                    {
                        excelworksheet.Cells[18, 3 + i] = dgvReport[i, j].Value;
                        addBorder(excelworksheet.Cells[18, 3 + i]);
                        continue;
                    }
                    if (dgvReport[1, j].Value.ToString().Equals("Productivity"))
                    {
                        excelworksheet.Cells[19, 3 + i] = dgvReport[i, j].Value;
                        addBorder(excelworksheet.Cells[19, 3 + i]);
                        continue;
                    }
                    if (dgvReport[1, j].Value.ToString().Equals("Profitability"))
                    {
                        excelworksheet.Cells[20, 3 + i] = dgvReport[i, j].Value;
                        addBorder(excelworksheet.Cells[20, 3 + i]);
                        continue;
                    }
                    if (dgvReport[1, j].Value.ToString().Equals("Investment"))
                    {
                        excelworksheet.Cells[21, 3 + i] = dgvReport[i, j].Value;
                        addBorder(excelworksheet.Cells[21, 3 + i]);
                        continue;
                    }
                }
            }

            excelworksheet.Columns.AutoFit();
            excelworksheet.Select(numPage);
        }

        string[] cultureNames = InformationClass.Lang ? DBClass.Cultures.Select(se => se.Name).Distinct().ToArray() : DBClass.Cultures.Select(se => se.Name).Distinct().ToArray();

        private void addBorder(object p)
        {
            Range tmpRange = excelworksheet.get_Range(p, p);
            tmpRange.Borders[XlBordersIndex.xlEdgeLeft].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeRight].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous;
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            if (dgvReport.RowCount > 0)
                PrintDGV.Print_DataGridView(dgvReport);
        }
    }
}
